package cn.elwy.rcp.ui.table.listener;

import java.util.List;
import java.util.Map;

import org.eclipse.jface.window.Window;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Item;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TreeColumn;

import cn.elwy.rcp.ui.table.TableConfigFactory;
import cn.elwy.rcp.ui.table.model.ColumnInfo;
import cn.elwy.rcp.ui.table.model.TableConfig;
import cn.elwy.rcp.ui.table.setting.ColumnSettingDialog;
import cn.elwy.rcp.ui.table.util.ColumnVisibleUtil;

public class TablePaneConfigListener extends TablePaneButtonListener {

  public TablePaneConfigListener() {
  }

  @Override
  public void widgetSelected(SelectionEvent event) {
    if (!tableInfo.isCanSettingColumn() || tablePane.getColumnOrder().length < 1) {
      return;
    }

    ColumnSettingDialog dialog = new ColumnSettingDialog(tablePane.getShell(), "表格设置", "设置列的显示或隐藏", getTablePane());
    if (Window.OK == dialog.open()) {
      TableConfig tableConfig = dialog.getTablePaneConfig();
      TableConfigFactory.mergeConfig(tableConfig, tablePane.getTableInfo());
      List<ColumnInfo> originalColumnList = tablePane.getTableInfo().getColumnInfoList();
      resetColumns(tableConfig.getColumnInfoList(), originalColumnList);
      tablePane.setConfigChanged(true);
    }
  }

  private void resetColumns(List<ColumnInfo> columns, List<ColumnInfo> originalColumnList) {
    int size = columns.size();
    int[] columnOrder = new int[size];
    Map<String, Item> treeColumnMap = tablePane.getTreeColumnMap();
    for (int i = 0; i < size; i++) {
      ColumnInfo column = columns.get(i);
      Item item = treeColumnMap.get(column.getId());
      if (item == null) {
        continue;
      }
      if (item instanceof TableColumn) {
        TableColumn tableColumn = (TableColumn) item;
        ColumnInfo info = (ColumnInfo) tableColumn.getData("columnInfo");
        tableColumn.setText(info.getName());
        tableColumn.setWidth(info.getWidth());
        columnOrder[i] = originalColumnList.indexOf(info);
        ColumnVisibleUtil.setColumnVisible(tableColumn, column.isVisible());
      } else {
        TreeColumn treeColumn = (TreeColumn) item;
        ColumnInfo info = (ColumnInfo) treeColumn.getData("columnInfo");
        treeColumn.setText(info.getName());
        treeColumn.setWidth(info.getWidth());
        columnOrder[i] = originalColumnList.indexOf(info);
        ColumnVisibleUtil.setColumnVisible(treeColumn, column.isVisible());
      }
    }
    tablePane.setColumnOrder(columnOrder);
  }

}